package com.zbkj.service.assistant.service;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.json.JSONUtil;
import com.zbkj.common.constants.AssistantConstants;
import com.zbkj.common.constants.Constants;
import com.zbkj.common.exception.CrmebException;
import com.zbkj.common.model.assistant.AssistantConversation;
import com.zbkj.common.model.assistant.AssistantMessage;
import com.zbkj.common.model.order.Order;
import com.zbkj.common.model.order.OrderDetail;
import com.zbkj.common.model.order.RefundOrder;
import com.zbkj.common.model.order.RefundOrderInfo;
import com.zbkj.common.model.product.Product;
import com.zbkj.common.netty.AcceptDataContent;
import com.zbkj.common.netty.AcceptMessage;
import com.zbkj.common.netty.CustomerServiceInfo;
import com.zbkj.common.netty.UserInfo;
import com.zbkj.common.result.AssistantResultCode;
import com.zbkj.service.assistant.dao.AssistantMessageDao;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zbkj.service.assistant.model.dto.AssistantMessageContentDTO;
import com.zbkj.service.assistant.model.request.AssistantConversationInitRequest;
import com.zbkj.service.assistant.model.request.AssistantMessageUserSendRequest;
import com.zbkj.service.assistant.model.vo.AssistantMessageVO;
import com.zbkj.service.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
* @author keNan
* @description AssistantMessageServiceImpl 接口实现
* @date 2025-06-11
*/
@Slf4j
@Service
public class AssistantMessageBaseServiceImpl extends ServiceImpl<AssistantMessageDao, AssistantMessage>{

    @Autowired
    private ProductService productService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private RefundOrderService refundOrderService;
    @Autowired
    private RefundOrderInfoService refundOrderInfoService;
    @Autowired
    private SystemAttachmentService systemAttachmentService;
    @Autowired
    private AssistantConversationBaseServiceImpl assistantConversationBaseService;
    @Autowired
    private SendMessageService sendMessageService;

    /**
     * 默认 只配置要不要给用户推送
     */
    public void sendBySystem(AssistantConversation conversation, Integer contentType, String content, Boolean isPushToUser) {
        sendBySystem(conversation, contentType, content, isPushToUser, null);
    }

    /**
     * 根据最后一个serviceContentType参数判断要不要给客服推送，如果为指定的类型，则可能会推送给客服
     */
    public void sendBySystem(AssistantConversation conversation, Integer contentType, String content, Boolean isPushToUser, Integer serviceContentType) {
        AssistantMessage param = new AssistantMessage()
            .setConversationId(conversation.getId())
            .setSenderType(AssistantConstants.Message.SENDER_TYPE_SYSTEM)
            .setUserId(conversation.getUserId())
            .setContentType(contentType)
            .setContent(content);
        super.save(param);
        AssistantMessage dbMessage = super.getById(param.getId());

        if (isPushToUser) {
            try {
                AcceptMessage acceptMessage = new AcceptMessage().setMessageContent(content).setAssistantMessage(dbMessage);
                UserInfo userInfo = new UserInfo().setType(1).setUserId(conversation.getUserId());
                AcceptDataContent acceptDataContent = new AcceptDataContent()
                    .setUserInfo(userInfo)
                    .setAcceptMessage(acceptMessage)
                    .setMessageType(contentType)
                    .setUserType(AssistantConstants.Message.SENDER_TYPE_SYSTEM)
                    .setToUserType(AssistantConstants.Message.SENDER_TYPE_USER)
                    .setSecret(Constants.CHANNEL_SECRET_SEND_MESSAGE);
                sendMessageService.sendMessage(acceptDataContent);
            } catch (Exception e) {
                log.error("发送消息给用户失败", e);
            }
        }

        if (ObjUtil.isNotEmpty(serviceContentType)) {
            try {
                if (AssistantConstants.Message.CONTENT_TYPE_SERVICE_REFRESH_CONVERSATION.equals(serviceContentType)) {
                    AcceptMessage acceptMessage = new AcceptMessage().setMessageContent(content).setAssistantMessage(dbMessage);
                    CustomerServiceInfo customerServiceInfo = new CustomerServiceInfo().setType(2).setUserId(conversation.getServiceAccountId());
                    AcceptDataContent acceptDataContent = new AcceptDataContent()
                        .setCustomerServiceInfo(customerServiceInfo)
                        .setAcceptMessage(acceptMessage)
                        .setMessageType(serviceContentType)
                        .setUserType(AssistantConstants.Message.SENDER_TYPE_SYSTEM)
                        .setToUserType(AssistantConstants.Message.SENDER_TYPE_SERVICE)
                        .setSecret(Constants.CHANNEL_SECRET_SEND_MESSAGE);
                    sendMessageService.sendMessage(acceptDataContent);
                }

            } catch (Exception e) {
                log.error("发送消息给客服失败", e);
            }
        }
    }

    @Transactional
    public AssistantMessageVO send(AssistantMessageUserSendRequest request, Integer userId, Boolean isPushNetty){
        AssistantConversation conversation = assistantConversationBaseService.getUserConversation(new AssistantConversationInitRequest(), userId);

        AssistantMessage param = new AssistantMessage()
            .setConversationId(conversation.getId())
            .setSenderType(1)
            .setUserId(userId)
            .setSenderId(userId)
            .setContentType(request.getContentType())
            .setContent(request.getContent())
            .setServiceAvatar(conversation.getServiceAvatar())
            .setServiceName(conversation.getServiceName())
            .setUserAvatar(conversation.getUserAvatar())
            .setUserName(conversation.getUserName());
        this.checkMessageContent(param);
        super.save(param);
        assistantConversationBaseService.updateAddMsgCount(conversation.getId(), 1, 0);
        AssistantMessage dbMessage = super.getById(param.getId());

        if (isPushNetty)
            this.processUserPushNetty(request.getContentType(), request.getContent(), dbMessage, userId, conversation.getServiceAccountId());

        AssistantMessageVO vo = new AssistantMessageVO();
        BeanUtil.copyProperties(dbMessage, vo);
        return vo;
    }

    /**
     * 检查消息内容，根据消息类型对消息内容进行封装
     * @param assistantMessage
     */
    protected void checkMessageContent(AssistantMessage assistantMessage) {
        if (assistantMessage.getContentType() == 2 || assistantMessage.getContentType() == 3) {
            String path = systemAttachmentService.clearPrefix(assistantMessage.getContent());
            assistantMessage.setContent(path);

        } else if (assistantMessage.getContentType() == 4) {
            // 发送商品
            Product product = productService.getById(assistantMessage.getContent());
            if (product == null)
                throw new CrmebException(AssistantResultCode.MESSAGE_CONTENT_TYPE_PRODUCT_NOT_EXIST);

            AssistantMessageContentDTO dto = new AssistantMessageContentDTO()
                .setProductId(product.getId())
                .setName(product.getName())
                .setImage(product.getImage())
                .setPrice(product.getPrice());
            assistantMessage.setContent(JSONUtil.toJsonStr(dto));

        } else if (assistantMessage.getContentType() == 5) {
            // 发送订单
            Order order = orderService.getByOrderNo(assistantMessage.getContent());
            if (order == null)
                throw new CrmebException(AssistantResultCode.MESSAGE_CONTENT_TYPE_ORDER_NOT_EXIST);
            List<OrderDetail> orderDetails = orderDetailService.getByOrderNo(order.getOrderNo());
            OrderDetail firstDetail = orderDetails.get(0);

            AssistantMessageContentDTO dto = new AssistantMessageContentDTO()
                .setProductId(firstDetail.getProductId())
                .setName(firstDetail.getProductName())
                .setImage(firstDetail.getImage())
                .setProductCount(order.getTotalNum())
                .setPrice(order.getPayPrice())
                .setOrderNo(order.getOrderNo())
                .setOrderStatus(order.getStatus())
                .setRefundStatus(order.getRefundStatus());
            assistantMessage.setContent(JSONUtil.toJsonStr(dto));
        } else if (assistantMessage.getContentType() == 6) {
            // 发送退款单
            RefundOrder refundOrder = refundOrderService.getByRefundOrderNo(assistantMessage.getContent());
            if (refundOrder == null)
                throw new CrmebException(AssistantResultCode.MESSAGE_CONTENT_TYPE_REFUND_ORDER_NOT_EXIST);

            RefundOrderInfo refundOrderInfo = refundOrderInfoService.getByRefundOrderNo(refundOrder.getRefundOrderNo());
            AssistantMessageContentDTO dto = new AssistantMessageContentDTO()
                .setProductId(refundOrderInfo.getProductId())
                .setName(refundOrderInfo.getProductName())
                .setImage(refundOrderInfo.getImage())
                .setProductCount(refundOrder.getTotalNum())
                .setPrice(refundOrder.getRefundPrice())
                .setOrderNo(refundOrder.getOrderNo())
                .setRefundOrderNo(refundOrder.getRefundOrderNo())
                .setRefundStatus(refundOrder.getRefundStatus());
            assistantMessage.setContent(JSONUtil.toJsonStr(dto));

        }
    }

    protected void checkUserReadMessage(AssistantMessage message) {
        if (!message.getIsUserRead()) {
            super.lambdaUpdate()
                .eq(AssistantMessage::getId, message.getId())
                .set(AssistantMessage::getIsUserRead, true)
                .set(AssistantMessage::getUserReadTime, new Date())
                .update();
        }
    }

    protected void processUserPushNetty(Integer contentType, String content, AssistantMessage message, Integer userId, Integer serviceAccountId) {
        try {
            AcceptMessage acceptMessage = new AcceptMessage().setMessageContent(content).setAssistantMessage(message);
            UserInfo userInfo = new UserInfo().setType(1).setUserId(userId);
            CustomerServiceInfo customerServiceInfo = new CustomerServiceInfo().setType(2).setUserId(serviceAccountId);
            AcceptDataContent acceptDataContent = new AcceptDataContent()
                .setUserInfo(userInfo)
                .setCustomerServiceInfo(customerServiceInfo)
                .setAcceptMessage(acceptMessage)
                .setMessageType(contentType)
                .setUserType(1)
                .setToUserType(2)
                .setSecret(Constants.CHANNEL_SECRET_SEND_MESSAGE);
            sendMessageService.sendMessage(acceptDataContent);
        } catch (Exception e) {
            log.error("发送消息失败", e);
        }
    }
}

